package com.android.manghe.search.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import androidx.recyclerview.widget.GridLayoutManager
import android.view.View
import android.view.inputmethod.EditorInfo
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.title.ETitleType
import com.android.base.tools.DisplayUtil
import com.android.base.tools.SerializeUtil
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.listener.OnItemClickListener
import com.android.manghe.R
import com.android.manghe.category.adapter.CategoryAuctionGridAdapter
import com.android.manghe.common.frame.activity.MVPWebSocketActivity
import com.android.manghe.config.Config
import com.android.manghe.common.model.AuctionSocketRes
import com.android.manghe.search.adapter.SearchHistoryGridAdapter
import com.android.manghe.search.presenter.PCategorySearch
import com.android.manghe.utils.ListUtil
import com.android.manghe.view.GridAuctionSpacesItemDecoration
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.zhangke.websocket.ErrorResponse
import com.zhangke.websocket.Response
import kotlinx.android.synthetic.main.activity_search.*
import java.util.*

class SearchCategoryActivity : MVPWebSocketActivity<PCategorySearch>(),IRefresh {
    override fun onMessageResponse(message: Response<*>?) {
        message?.let {
            p.dealSocketData(it.responseText)
        }
    }

    override fun onSendMessageError(error: ErrorResponse?) {

    }

    private var mAdapter: CategoryAuctionGridAdapter? = null

    override fun getRefreshView(): SmartRefreshLayout {
        return findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        p.search(true,"")
    }

    override fun onLoad() {
        p.search(false,"")
    }
    private var mHistoryAdapter: SearchHistoryGridAdapter? = null

    private var mSearchHistoryList = arrayListOf<String>()

    companion object {
        fun showActivity(context: Context) {
            val intent = Intent(context, SearchCategoryActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun showToolBarType(): ETitleType {
        return ETitleType.NO_TITLE
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_search
    }

    override fun initData(savedInstanceState: Bundle?) {
        val localHistoryListTemp = SerializeUtil.loadFile(Config.SerializeSearchHistory)
        localHistoryListTemp?.let {
            mSearchHistoryList.addAll(it as List<String>)
        }
        layoutHistory.visibility = if (mSearchHistoryList.isNullOrEmpty()) View.GONE else View.VISIBLE
        if (!mSearchHistoryList.isNullOrEmpty()) {
                recyclerView.layoutManager = GridLayoutManager(
                    this,
                    3
                )!!
                mHistoryAdapter = SearchHistoryGridAdapter(mSearchHistoryList)
                recyclerView.adapter = mHistoryAdapter
        }

        recyclerViewData.layoutManager =
            GridLayoutManager(this, 2)
        recyclerViewData.addItemDecoration(GridAuctionSpacesItemDecoration(DisplayUtil.dip2px(this, 8f)))
        mAdapter = CategoryAuctionGridAdapter(
            this,
            ArrayList<AuctionSocketRes.ListBean>()
        )
        mAdapter!!.setUseFromSearch()
        recyclerViewData.adapter = mAdapter

        initListener()

        handler.sendEmptyMessageDelayed(1, 1000)
    }

    fun initListener() {
        tvCancel.setOnClickListener { finish() }
        etSearch.setOnEditorActionListener { _, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val text = etSearch.text.toString().trim()
                if(text.isEmpty()){
                    ToastUtil.showShort(this@SearchCategoryActivity, "请输入搜索内容")
                    true
                }else {
                    mSearchHistoryList.add(text)
                    ListUtil.removeDuplicate(mSearchHistoryList)
                    SerializeUtil.saveFile(mSearchHistoryList, Config.SerializeSearchHistory)
                    mHistoryAdapter?.update(mSearchHistoryList)
                    search(text)
                    true
                }
            }
            false
        }
        mHistoryAdapter?.let {
            it.setOnItemClickListener(OnItemClickListener<String> { view, text ->
                search(text)
            })
        }
    }

    private fun search(text: String){
        showLoadingDialog()
        layoutHistory.visibility = View.GONE
        refreshLayout.visibility = View.VISIBLE
        p.search(true, text)
    }

    fun searchFail(text: String?){
        hideLoadingDialog()
        layoutHistory.visibility = View.VISIBLE
        refreshLayout.visibility = View.GONE
        ToastUtil.showShort(this, if(text.isNullOrEmpty()) "搜索失败" else text)
    }

    fun searchOk(data: List<AuctionSocketRes.ListBean>){
        hideLoadingDialog()
        mAdapter?.let {
            it.update(data)
        }
    }
    fun noData(){
        hideLoadingDialog()
        layoutHistory.visibility = View.VISIBLE
        refreshLayout.visibility = View.GONE
        ToastUtil.showShort(this, "无搜索结果")
    }
    fun modifyItemData(itemData: AuctionSocketRes.ListBean,position: Int){
        mAdapter?.let {
            it.mAuctionList[position] = itemData
            it.update(it.mAuctionList)
        }
    }
    var resultX = -1
    private val handler = object : Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            mAdapter?.let {
                if (msg?.what == 1) {
                    resultX = it?.countDownTime()
                    if (resultX == 0) {
                        removeMessages(1)
                        return
                    } else {
                        it?.notifyDataSetChanged();
                        sendEmptyMessageDelayed(1, 1000)
                    }
                }
            }
        }
    }


}